#pragma once

#include <iostream>
#include "Socket.hpp"
#include "epoller.hpp"
#include <memory>
#include "nocopy.hpp"

const static int defaultport = 8888;

class Epollserver : public nocopy
{
    const static int num = 64;

public:
    Epollserver(const uint16_t port = defaultport)
        : _listensocket(new Sock()),
          _epoll_ptr(new Epoll()),
          _port(port)
    {
    }

    ~Epollserver()
    {
        _listensocket->Close();
    }

    void Init()
    {
        _listensocket->Socket();
        _listensocket->Bind(_port);
        _listensocket->Listen();
    }

    void Accepter()
    {
        uint16_t clientport;
        std::string clientip;
        int newfd = _listensocket->Accept(&clientip, &clientport);
        if (newfd > 0)
        {
            _epoll_ptr->EpollUpdate(EPOLL_CTL_ADD, newfd, EPOLLIN);
        }
    }

    void Recver(int fd)
    {
        char buffer[1024];
        int n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n - 1] = '\0';
            std::cout << "get a message: " << buffer << std::endl;

            std::string echo = "server echo $ ";
            echo += buffer;
            write(fd, echo.c_str(), echo.size());
        }
        else if (n == 0)
        {
            lg(Info, "client quit, me too! close :%d", fd);
            _epoll_ptr->EpollUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
        else
        {
            lg(Warning, "recv error,  close :%d", fd);
            _epoll_ptr->EpollUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
    }

    void Handler(struct epoll_event revs[], int num)
    {
        for (int i = 0; i < num; i++)
        {
            if (revs[i].events & EPOLLIN)
            {
                if (revs[i].data.fd == _listensocket->Getfd())
                {
                    Accepter();
                }
                else
                {
                    Recver(revs[i].data.fd);
                }
            }
            else if (revs[i].events & EPOLLOUT)
            {
                // TODO
            }
            else
            {
                // TODO
            }
        }
    }

    void Start()
    {
        _epoll_ptr->EpollUpdate(EPOLL_CTL_ADD, _listensocket->Getfd(), EPOLLIN);
        struct epoll_event revs[num];

        for (;;)
        {
            int n = _epoll_ptr->EpollWait(revs, num, 3000);
            if (n > 0)
            {
                lg(Info, "get a new link!!!");
                Handler(revs, n);
            }
            else if (n == 0)
            {
                lg(Info, "time out...");
                continue;
            }
            else if (n < 0)
            {
                continue;
            }
        }
    }

private:
    std::shared_ptr<Sock> _listensocket;
    std::shared_ptr<Epoll> _epoll_ptr;
    uint16_t _port;
};
